package com.resource.transactions.security;

import com.resource.transactions.entities.Permission;
import com.resource.transactions.entities.RRole;
import com.resource.transactions.entities.RUser;
import com.resource.transactions.service.RRoleService;
import com.resource.transactions.service.RUserService;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Component
public class UserDetailServiceImpl implements UserDetailsService {

    @Resource
    private RUserService rUserService;

    @Resource
    private RRoleService rRoleService;

    @Override
    public UserDetails loadUserByUsername(String userEmail) throws UsernameNotFoundException {
        RUser rUser = rUserService.rUserAndRRoleSelectAllInFoByRUserEmail(userEmail);
        User user;
        if (rUser == null) {
            throw new UsernameNotFoundException("该用户不存在");
        } else {
            List<GrantedAuthority> authorities = new ArrayList<>();
            for (RRole rRole : rUser.getRRoleList()) {
                for (Permission permission : rRoleService.rRoleAndPerPermissionSelectAllInFoByRRoleId(rRole.getRoleid()).getPermissionList()) {
                    authorities.add(new SimpleGrantedAuthority(permission.getPermissionname()));
                }
            }
            user = new User(rUser.getUseremail(), rUser.getUserpasw(), authorities);
        }
        return user;
    }

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
